<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="车位编号" prop="plateNumber">
        <el-input
          v-model="queryParams.plateNumber"
          placeholder="请输入车位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约时间" prop="reservationDate">
        <el-date-picker
          clearable
          v-model="queryParams.reservationDate"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm"
          placeholder="请选择预约时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约状态" prop="reservationStatus">
        <el-select
          v-model="queryParams.reservationStatus"
          placeholder="请选择预约状态"
          clearable
        >
          <el-option
            v-for="(option, index) in statusOptions"
            :key="index"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="reservationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预约ID" align="center" prop="scReservationId" />
      <el-table-column label="用户名" align="center" prop="scUsername" />
      <el-table-column label="车牌号码" align="center" prop="scLicensePlate" />
      <el-table-column label="用户预定车位的时间" align="center" prop="scReservationTime">
      </el-table-column>
      <el-table-column label="预定车位编号" align="center" prop="scSpaceNumber" />
      <el-table-column label="预约定金（元）" align="center" prop="scDeposit" />
      <el-table-column label="违约金（元）" align="center" prop="scPenalty" />
      <el-table-column label="预约的状态" align="center" prop="scReservationStatus">
        <template slot-scope="scope">
          <el-button
            :type="getStatusButtonType(scope.row.scReservationStatus)"
            :disabled="scope.row.scReservationStatus !== 0"
            size="mini"
          >
            {{ getStatusLabel(scope.row.scReservationStatus) }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="取消时间间隔（分钟）"
        align="center"
        prop="scCancelInterval"
      />

      <el-table-column label="违约金（元）" align="center" prop="scPenalty" />

      <el-table-column label="预约信息更新时间" align="center" prop="scUpdateTime">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加车辆预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预约定金（元）" prop="deposit">
          <el-input-number
            v-model="form.deposit"
            placeholder="请输入预约定金"
            :min="0"
            :precision="2"
          />
        </el-form-item>
        <el-form-item label="违约金（元）" prop="penalty">
          <el-input-number
            v-model="form.penalty"
            placeholder="请输入违约金"
            :min="0"
            :precision="2"
          />
        </el-form-item>

        <el-form-item label="取消时间间隔（分钟）" prop="cancellationInterval">
          <el-input-number
            v-model="form.cancellationInterval"
            placeholder="请输入取消时间间隔"
            :min="1"
          />
        </el-form-item>

        <el-form-item label="预约状态" prop="reservationStatus">
          <el-select
            v-model="form.reservationStatus"
            placeholder="请选择预约状态"
            clearable
          >
            <el-option
              v-for="(option, index) in statusOptions"
              :key="index"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAction">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { lstReservation, updateReservation } from "@/api/system/reservation";
export default {
  name: "VehicleReservation",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆预约表格数据
      reservationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isEdit: false, // 标记当前是添加还是修改操作
      // 表单数据
      form: {
        reservationId: "",
        plateNumber: "",
        reservationDate: "",
        parkingSpace: "",
        deposit: "",
        penalty: "",
        reservationStatus: "",
        cancellationInterval: "",
        ScUserName: "",
      },
      // 查询参数
      queryParams: {
        scUserName: "",
        reservationDate: null,
        reservationStatus: null,
      },

      // 表单校验
      rules: {
        plateNumber: [{ required: true, message: "车牌号码不能为空", trigger: "blur" }],
        reservationDate: [
          { required: true, message: "用户预定车位的时间不能为空", trigger: "blur" },
        ],
        parkingSpace: [
          { required: true, message: "预定的车位不能为空", trigger: "blur" },
        ],
        deposit: [{ required: true, message: "预约定金不能为空", trigger: "blur" }],
        penalty: [{ required: true, message: "违约金不能为空", trigger: "blur" }],
        reservationStatus: [
          { required: true, message: "预约的状态不能为空", trigger: "blur" },
        ],
        cancellationInterval: [
          { required: true, message: "取消时间间隔不能为空", trigger: "blur" },
        ],
      },
      // 预约时段类型选项
      statusOptions: [
        { label: "空闲", value: 0 },
        { label: "已预订", value: 1 },
        { label: "已占用", value: 2 },
        { label: "维护中", value: 3 },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      lstReservation(
        this.queryParams.scUserName,
        this.queryParams.reservationDate,
        this.queryParams.reservationStatus
      ).then((response) => {
        console.log(response.rows);
        this.reservationList = response.rows;
      });
    },

    // 时间格式化函数，可根据需要调整
    parseTime(time, fmt) {
      if (!time) return "";
      const format = fmt || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        if (typeof time === "string") {
          if (/(Y|y|M|m|d|D|h|H|i|s|S)/.test(time)) {
            date = new Date(time);
          } else {
            date = new Date(parseInt(time));
          }
        } else if (typeof time === "number") {
          date = new Date(time);
        }
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        S: date.getMilliseconds(),
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|S)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "m" || key === "h" || key === "i" || key === "s" || key === "S") {
          value = value.toString().padStart(2, "0");
        }
        return value;
      });
      return time_str;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.plateNumber);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.isEdit = false;
      this.reset();
      this.open = true;
      this.title = "添加车辆预约";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {
        reservationId: row.scReservationId,
        plateNumber: row.scLicensePlate,
        reservationDate: row.scReservationTime,
        parkingSpace: row.scSpaceNumber,
        deposit: row.scDeposit,
        penalty: row.scPenalty,
        reservationStatus: row.scReservationStatus,
        cancellationInterval: row.scCancelInterval,
      };
      this.isEdit = true;
      this.open = true;
      this.title = "修改车辆预约信息";
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        reservationId: null,
        plateNumber: null,
        reservationDate: null,
        parkingSpace: null,
        deposit: null,
        penalty: null,
        reservationStatus: null,
        cancellationInterval: null,
      };
      this.resetForm("form");
    },

    // 确定按钮点击事件
    submitAction() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            const updateData = {
              scReservationId: this.form.reservationId,
              scDeposit: this.form.deposit,
              scPenalty: this.form.penalty,
              scCancelInterval: this.form.cancellationInterval,
              scReservationStatus: this.form.reservationStatus, // 添加预约状态到更新数据中
            };
            updateReservation(updateData)
              .then(() => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              })
              .catch((error) => {
                console.error("更新预约信息失败", error);
                this.$message.error("修改失败，请重试");
              });
          } else {
            // 这里可添加新增的实际逻辑
            this.$message.success("新增成功");
            this.open = false;
            this.getList();
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除车牌号码为"' + row.scLicensePlate + '"的预约数据项？',
        "提示",
        { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
      )
        .then(() => {
          // 这里可添加删除的实际逻辑
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {
          // 取消操作，不做处理
        });
    },
    getStatusButtonType(status) {
      switch (status) {
        case 0:
          return "success";
        case 1:
          return "warning";
        case 2:
          return "danger";
        case 3:
          return "info";
        default:
          return "default";
      }
    },
    getStatusLabel(status) {
      switch (status) {
        case 0:
          return "空闲";
        case 1:
          return "已预订";
        case 2:
          return "已占用";
        case 3:
          return "维护中";
        default:
          return "未知状态";
      }
    },
  },
};
</script>

<style scoped>
/* 可根据需要添加或修改样式 */
</style>
